package com.vvv.designpattern.terminationpattern;

class TwoPhraseTermination {

    public static void main(String[] args) throws InterruptedException {
        TwoPhraseTermination tpt = new TwoPhraseTermination();
        tpt.start();
        Thread.sleep(3500);
        tpt.stop();
    }

    private Thread t1;

    public void start() {
        t1 = new Thread(() -> {
            while (true) {
                Thread currentThread = Thread.currentThread();
                if (currentThread.isInterrupted()) {
                    System.out.println("t1 料理后事");
                    break;
                }
                try {
                    // 这里线程在阻塞中，也可以会被interrupt
                    Thread.sleep(1000);
                    // 这里线程在工作中，可能会被interrupt
                    System.out.println("t1 监控中...");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    // 在阻塞状态中重新设置interrupt状态为true
                    currentThread.interrupt();
                }
            }
        }, "t1");
        t1.start();
    }

    public void stop() {
        t1.interrupt();
    }
}